import {
  Popconfirm,
  Space,
  TableColumnsType,
  Tag,
  Tooltip,
  Typography,
  Image,
  Badge,
  Input,
  InputNumber,
  Cascader,
} from 'antd'
import { NavigateFunction } from 'react-router-dom'
import type { ITableData, ITableAddType, SupplierTransportAddressVO } from './types'
import {
  BadgeColorMap,
  BadgeColorDeliveryMap,
  DIS_STATUSBANDBTNTEXT,
  STATUSBAND,
  USERTYPETEXT,
  LogisticsDemandStatusMap,
} from '@/constant'
import { getImageByUrl } from '@/utils/getImageByUrl'
import { FIRST_ORDER_RETURN_ORDER_TEXT, ORDER_STATUS_TEXT, RESERVE_INVOICE_STATUS_TEXT } from '@/constant/purchase'
import React from 'react'
import PermissionLink from '@/components/PermissionLink'
import { IOptionArea } from '@/hooks/useGetArea'
export const useIndexColumns = ({
  navigate,
  onView,
  onViewLogs,
  onConfirmDelivery,
  onSubmitPacking,
  onDel,
  onFix,
  isRoot,
}: {
  navigate: NavigateFunction
  onView: (info: ITableData) => void
  onViewLogs: (info: ITableData) => void
  onConfirmDelivery: (info: ITableData) => void
  onSubmitPacking: (info: ITableData) => void
  onDel: (info: ITableData) => void
  onFix: (info: ITableData) => void
  isRoot: boolean
}): TableColumnsType<ITableData> => [
  {
    title: '预约发货单',
    dataIndex: 'reserveInvoiceCode',
    key: 'reserveInvoiceCode',
    align: 'center',
    fixed: 'left',
    width: 250,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 200,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '供应链交期',
    dataIndex: 'deliveryTime',
    key: 'deliveryTime',
    align: 'center',
    width: 140,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '供应商',
    dataIndex: 'supplierName',
    key: 'supplierName',
    align: 'center',
    width: 200,
    ellipsis: {
      showTitle: false,
    },
    render: (info) => {
      return info ? (
        <Tooltip placement="top" title={info}>
          {info}
        </Tooltip>
      ) : (
        '-'
      )
    },
  },
  {
    title: '首单/返单',
    dataIndex: 'orderType',
    key: 'orderType',
    align: 'center',
    width: 120,
    render: (info) => {
      return FIRST_ORDER_RETURN_ORDER_TEXT[info] || '-'
    },
  },
  {
    title: '供应链跟单',
    dataIndex: 'trackOrderPerson',
    key: 'trackOrderPerson',
    align: 'center',
    width: 100,
    render: (info) => {
      return info ? info : '-'
    },
  },
  {
    title: '订单状态',
    dataIndex: 'reserveInvoiceStatus',
    key: 'reserveInvoiceStatus',
    align: 'center',
    width: 120,
    render: (info) => {
      return <Badge color={BadgeColorDeliveryMap[info]} text={RESERVE_INVOICE_STATUS_TEXT[info] || '-'} /> || '-'
    },
  },
  {
    title: '推送状态',
    dataIndex: 'pushErrorMsg',
    key: 'pushErrorMsg',
    align: 'center',
    width: 150,
    hidden: !isRoot,
    render: (info) => {
      return info ? (
        <Tooltip placement="top" title={info}>
          <Tag color="error">推送CB失败</Tag>
        </Tooltip>
      ) : (
        '-'
      )
    },
  },
  {
    title: '预约发货时间',
    dataIndex: 'scheduleDeliveryTime',
    key: 'scheduleDeliveryTime',
    align: 'center',
    width: 180,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '款式编码',
    dataIndex: 'spuCode',
    key: 'spuCode',
    align: 'center',
    width: 120,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '预计到货时间',
    dataIndex: 'estimatedArrivalTime',
    key: 'estimatedArrivalTime',
    align: 'center',
    width: 120,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '箱数',
    dataIndex: 'totalBoxQty',
    key: 'totalBoxQty',
    align: 'center',
    width: 100,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '预约总数',
    dataIndex: 'totalScheduleQty',
    key: 'totalScheduleQty',
    align: 'center',
    width: 100,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '已扫码数量',
    dataIndex: 'totalScanQty',
    key: 'totalScanQty',
    align: 'center',
    width: 100,
    render: (info) => {
      return info == 0 ? 0 : info || '-'
    },
  },
  {
    title: '到货总数',
    dataIndex: 'totalArriveQty',
    key: 'totalArriveQty',
    align: 'center',
    width: 100,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '实际到货时间',
    dataIndex: 'lastArrivalTime',
    key: 'lastArrivalTime',
    align: 'center',
    width: 180,
    render: (info, rows) => {
      return (
        <Tooltip title={rows?.updateArrivalTimeRemark}>
          <span style={{ color: rows?.updateArrivalTimeRemark ? 'red' : '' }}>{info || '-'}</span>
        </Tooltip>
      )
    },
  },
  {
    title: '仓库上架时间',
    dataIndex: 'warehouseShelvingTime',
    key: 'warehouseShelvingTime',
    align: 'center',
    width: 180,
    hidden: !isRoot,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '物流需求单号',
    dataIndex: 'transportationOrderCode',
    key: 'transportationOrderCode',
    align: 'center',
    width: 240,
    render: (info, rows) => {
      return info
        ? info + (rows?.transportStatus >= 0 ? '（' + LogisticsDemandStatusMap[rows?.transportStatus] + '）' : '')
        : '-'
    },
  },
  {
    title: '物流信息',
    dataIndex: 'status',
    key: 'status',
    align: 'center',
    fixed: 'right',
    width: 100,
    render: (_, rows) => {
      return (
        <Space size={'large'}>
          <Typography.Link onClick={() => onView(rows)}>查看</Typography.Link>
        </Space>
      )
    },
  },
  {
    title: '操作',
    fixed: 'right',
    align: 'center',
    width: 250,
    render: (_, rows) => {
      return (
        <Space size={'large'}>
          {rows.reserveInvoiceStatus === 2 ? (
            <PermissionLink permission="confirmDeliver" onClick={() => onConfirmDelivery(rows)}>
              确认发货
            </PermissionLink>
          ) : null}
          {rows.reserveInvoiceStatus === 6 ? (
            <PermissionLink permission="submitPacking" onClick={() => onSubmitPacking(rows)}>
              提交装箱
            </PermissionLink>
          ) : null}
          {rows.reserveInvoiceStatus != 4 && rows.reserveInvoiceStatus != 5 ? (
            <PermissionLink permission="cancelDeliver" type="danger" onClick={() => onDel(rows)}>
              取消预约
            </PermissionLink>
          ) : null}
          {rows.reserveInvoiceStatus == 4 ? (
            <PermissionLink permission="fixDeliverTime" onClick={() => onFix(rows)}>
              修正到货时间
            </PermissionLink>
          ) : null}
          {isRoot ? <Typography.Link onClick={() => onViewLogs(rows)}>查看日志</Typography.Link> : null}
        </Space>
      )
    },
  },
]

export const useInnerColumns = (): TableColumnsType<ITableData> => [
  {
    title: '采购订单号',
    dataIndex: 'purchaseOrderCode',
    key: 'purchaseOrderCode',
    align: 'center',
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '款式编码',
    dataIndex: 'productSimpleVO',
    key: 'spuCode',
    align: 'center',
    render: (info) => {
      return info?.spuCode || '-'
    },
  },
  {
    title: '助记码',
    dataIndex: 'productSimpleVO',
    key: 'designCode',
    align: 'center',
    render: (info) => {
      return info?.designCode || '-'
    },
  },
  {
    title: '工厂款号',
    dataIndex: 'productSimpleVO',
    key: 'factorySpuCode',
    align: 'center',
    render: (info) => {
      return info?.factorySpuCode || '-'
    },
  },
  {
    title: '款式名称',
    dataIndex: 'productSimpleVO',
    key: 'spuName',
    align: 'center',
    render: (info) => {
      return info?.spuName || '-'
    },
  },
  {
    title: '商品分类',
    dataIndex: 'productSimpleVO',
    key: 'className',
    align: 'center',
    render: (info) => {
      return info?.className || '-'
    },
  },
  {
    title: '商品条码',
    dataIndex: 'productSimpleVO',
    key: 'skuCode',
    align: 'center',
    render: (info) => {
      return info?.skuCode || '-'
    },
  },
  {
    title: '尺码',
    dataIndex: 'productSimpleVO',
    key: 'size',
    align: 'center',
    render: (info) => {
      return info?.size || '-'
    },
  },
  {
    title: '颜色',
    dataIndex: 'productSimpleVO',
    key: 'colorDetailName',
    align: 'center',
    render: (info) => {
      return info?.colorDetailName || '-'
    },
  },
  {
    title: '预约发货数量',
    dataIndex: 'scheduleQty',
    key: 'scheduleQty',
    align: 'center',
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '已扫码数量',
    dataIndex: 'scanQty',
    key: 'scanQty',
    align: 'center',
    width: 150,
    render: (info) => {
      return info == 0 ? 0 : info || '-'
    },
  },
  {
    title: '内箱数',
    dataIndex: 'productSimpleVO',
    key: 'inPackageNum',
    align: 'center',
    render: (info) => {
      return info?.inPackageNum || '-'
    },
  },
  {
    title: '外箱数',
    dataIndex: 'productSimpleVO',
    key: 'outPackageNum',
    align: 'center',
    render: (info) => {
      return info?.outPackageNum || '-'
    },
  },
  {
    title: '箱数',
    dataIndex: 'boxQty',
    key: 'boxQty',
    align: 'center',
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '到货数量',
    dataIndex: 'arriveQty',
    key: 'arriveQty',
    align: 'center',
    render: (info) => {
      return info || '-'
    },
  },
]

export const useSendColumns = ({
  tableData,
  settableData,
  selectedRowKeys,
}: {
  tableData: ITableAddType[]
  settableData: React.Dispatch<React.SetStateAction<ITableAddType[]>>
  selectedRowKeys: React.Key[]
}): TableColumnsType<ITableData> => [
  {
    title: '供应商',
    dataIndex: 'supplierName',
    key: 'supplierName',
    align: 'center',
    width: 250,
    ellipsis: {
      showTitle: false,
    },
    render: (info) => {
      return info ? (
        <Tooltip placement="top" title={info}>
          {info}
        </Tooltip>
      ) : (
        '-'
      )
    },
  },
  {
    title: '采购订单号',
    dataIndex: 'purchaseOrderCode',
    key: 'purchaseOrderCode',
    align: 'center',
    width: 220,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '供应链交期',
    dataIndex: 'deliveryTime',
    key: 'deliveryTime',
    align: 'center',
    width: 140,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '款式编码',
    dataIndex: 'spuCode',
    key: 'spuCode',
    align: 'center',
    width: 140,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '助记码',
    dataIndex: 'memoryCode',
    key: 'memoryCode',
    align: 'center',
    width: 140,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '工厂款号',
    dataIndex: 'factorySpuCode',
    key: 'factorySpuCode',
    align: 'center',
    width: 140,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '商品名称',
    dataIndex: 'productName',
    key: 'productName',
    align: 'center',
    width: 200,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '商品分类',
    dataIndex: 'wholeClassName',
    key: 'wholeClassName',
    align: 'center',
    width: 200,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '商品条码',
    dataIndex: 'skuCode',
    key: 'skuCode',
    align: 'center',
    width: 160,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '尺码',
    dataIndex: 'commoditySize',
    key: 'commoditySize',
    align: 'center',
    width: 100,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '颜色',
    dataIndex: 'colorDetailName',
    key: 'colorDetailName',
    align: 'center',
    width: 120,
    render: (info) => {
      return info || '-'
    },
  },
  {
    title: '吊牌价',
    dataIndex: 'tagPrice',
    key: 'tagPrice',
    align: 'center',
    width: 120,
    render: (info) => {
      return info || '-'
    },
  },
  // {
  //   title: '采购价',
  //   dataIndex: 'purchasePrice',
  //   key: 'purchasePrice',
  //   align: 'center',
  //   width: 200,
  //   render: (info) => {
  //     return info || '-'
  //   },
  // },
  {
    title: '下单数量',
    dataIndex: 'orderQty',
    key: 'orderQty',
    align: 'center',
    fixed: 'right',
    width: 120,
    render: (info) => {
      return info || 0
    },
  },
  {
    title: '已预约数量',
    dataIndex: 'scheduledQty',
    key: 'scheduledQty',
    align: 'center',
    fixed: 'right',
    width: 120,
    render: (info) => {
      return info || 0
    },
  },
  {
    title: '待预约数量',
    dataIndex: 'dyy',
    key: 'dyy',
    align: 'center',
    fixed: 'right',
    width: 120,
    render: (_, rows) => {
      return rows.orderQty - rows.scheduledQty >= 0 ? rows.orderQty - rows.scheduledQty : 0
    },
  },
  {
    title: '本次预约数量',
    dataIndex: 'scheduleQty',
    key: 'scheduleQty',
    align: 'center',
    fixed: 'right',
    width: 120,
    render: (info, rows, index) => {
      return selectedRowKeys?.includes(rows?.id) ? (
        <InputNumber
          defaultValue={info}
          onChange={(value: any) => {
            if (value <= 0) return
            rows['isEdit'] = false
            rows.scheduleQty = Math.ceil(value)
            settableData([...tableData])
          }}
          precision={0}
          min={1}
        ></InputNumber>
      ) : (
        <div
          className="edit_intable_style"
          onClick={() => {
            rows['isEdit'] = true
            settableData([...tableData])
          }}
        >
          {info}
        </div>
      )
    },
  },
]

export const useDetailsColumns = (): TableColumnsType<any> => {
  return [
    {
      title: '预约发货单',
      dataIndex: 'reserveInvoiceCode',
      key: 'reserveInvoiceCode',
      align: 'center',
      width: 150,
      render: (info) => info || '-',
    },
    {
      title: '款式编码',
      dataIndex: 'spuCode',
      key: 'spuCode',
      align: 'center',
      width: 150,
      render: (info) => info || '-',
    },
    {
      title: '款式名称',
      dataIndex: 'spuName',
      key: 'spuName',
      align: 'center',
      width: 220,
      render: (_, rows) => {
        return rows?.detailVOS?.[0]?.productSimpleVO?.className || rows?.spuName || '-'
      },
    },
    {
      title: '预约发货时间',
      dataIndex: 'scheduleDeliveryTime',
      key: 'scheduleDeliveryTime',
      align: 'center',
      width: 150,
      render: (info) => info || '-',
    },
    {
      title: '箱数',
      dataIndex: 'totalBoxQty',
      key: 'totalBoxQty',
      align: 'center',
      width: 150,
      render: (info) => info || '-',
    },
    {
      title: '预约总数',
      dataIndex: 'totalScheduleQty',
      key: 'totalScheduleQty',
      align: 'center',
      width: 150,
      render: (info) => info || '-',
    },
  ]
}

export const useAddressColumns = ({
  addressList,
  setaddressList,
  AreaOptions,
  loadAreaData,
  setareaList,
  onSave,
  onDel,
}: {
  addressList: SupplierTransportAddressVO[]
  setaddressList: React.Dispatch<React.SetStateAction<SupplierTransportAddressVO[]>>
  AreaOptions: IOptionItem[]
  loadAreaData: (info: IOptionArea[]) => void
  setareaList: React.Dispatch<React.SetStateAction<number[]>>
  onSave: (rows: SupplierTransportAddressVO, isReload?: boolean) => void
  onDel: (rows: SupplierTransportAddressVO) => void
}): TableColumnsType<any> => {
  return [
    {
      title: '提货地址',
      dataIndex: 'address',
      key: 'address',
      width: 600,
      render: (_, rows) => {
        return (
          <div>
            <span style={{ marginRight: 6 }}>
              {rows.isEdit ? (
                <Space>
                  <Input
                    style={{ width: 140 }}
                    value={rows.contacts || null}
                    onChange={(event) => {
                      rows.contacts = event.target.value
                      setaddressList([...addressList])
                    }}
                  ></Input>
                  <Input
                    style={{ width: 140 }}
                    value={rows.phone || null}
                    onChange={(event) => {
                      rows.phone = event.target.value
                      setaddressList([...addressList])
                    }}
                  ></Input>
                  <Cascader
                    defaultValue={[Number(rows.provinceId), Number(rows.cityId), Number(rows.areaId)]}
                    options={AreaOptions}
                    loadData={loadAreaData}
                    changeOnSelect
                    placeholder="请选择收货地址"
                    style={{ width: 220 }}
                    onChange={(vals, items) => {
                      rows.receivingAddress = vals
                      if (vals && vals.length > 0) {
                        if (vals[0]) {
                          rows.provinceId = vals[0]
                          rows.province = items[0]?.label
                        }
                        if (vals[1]) {
                          rows.cityId = vals[1]
                          rows.city = items[1]?.label
                        }
                        if (vals[2]) {
                          rows.areaId = vals[2]
                          rows.area = items[2]?.label
                        }
                      }
                    }}
                  ></Cascader>
                  <Input.TextArea
                    rows={1}
                    showCount
                    maxLength={100}
                    style={{ width: 300 }}
                    value={rows.address || null}
                    onChange={(event) => {
                      rows.address = event.target.value
                      setaddressList([...addressList])
                    }}
                  ></Input.TextArea>
                </Space>
              ) : (
                <Space>
                  <span>{rows.contacts}</span>
                  <span>{rows.phone}</span>
                  <span>
                    {rows.province}
                    {rows.city}
                    {rows.area}
                  </span>
                  <span>{rows.address}</span>
                </Space>
              )}
            </span>
          </div>
        )
      },
    },
    {
      title: '操作',
      dataIndex: 'spuCode',
      key: 'spuCode',
      fixed: 'right',
      width: 100,
      render: (_, rows) => {
        return (
          <Space>
            <Typography.Link
              onClick={() => {
                if (!rows['isEdit']) {
                  // 点击了编辑
                  rows.isEdit = true
                  const receivingAddress = [Number(rows.provinceId), Number(rows.cityId), Number(rows.areaId)]
                  setareaList(receivingAddress)
                  rows.receivingAddress = receivingAddress
                  setaddressList([...addressList])
                } else {
                  onSave(rows)
                }
              }}
            >
              {rows['isEdit'] ? '保存' : '编辑'}
            </Typography.Link>
            {rows['isEdit'] && (
              <Typography.Link
                onClick={() => {
                  rows['isEdit'] = !rows['isEdit']
                  onSave(rows, true)
                }}
              >
                取消
              </Typography.Link>
            )}

            <Popconfirm title={`确认删除吗？`} onConfirm={() => onDel(rows)} okText="确认" cancelText="取消">
              <Typography.Link type="danger">删除</Typography.Link>
            </Popconfirm>
          </Space>
        )
      },
    },
  ]
}
